'use strict';
const uniID = require('uni-id-common')
exports.main = async (event, context) => {
	const uniIDIns = uniID.createInstance({
		context: context,
	})
	const res = await uniIDIns.checkToken(event.uniIdToken)
	const db = uniCloud.databaseForJQL({
			event,
			context 
		});
		db.setUser({
			role: ['admin']
		})
	let userinfo = await db.collection("uni-id-users").where({
		_id: res.uid
	}).get();
	if(event.type==0){
		await db.collection("uni-id-users").where({
			_id: res.uid
		}).update({
			point: userinfo.data[0].point+event.value
		})
		await db.collection("bill").add({
			time: new Date,
			title: event.title,
			content: String(event.value),
			user_id: res.uid,
			type: "+",
			bill_type:"point"
		})
		return {msg:"操作成功",code:200}
	}else{
		var value;
		if((userinfo.data[0].point-event.value)<0){
			value=0
			return {msg:"积分不足",code:400}
		}else{
			value=userinfo.data[0].point-event.value
		}
		await db.collection("uni-id-users").where({
			_id: res.uid
		}).update({
			point:value
		})
		await db.collection("bill").add({
			time: new Date,
			title: event.title,
			content:String(event.value),
			user_id: res.uid,
			type: "-",
			bill_type:"point"
		})
		return {msg:"操作成功",code:200}
	}
};
// const userid = await uniCloud.callFunction({
// 				name: 'point',
// 				data:{
// 					title:"测试积分",
// 					type:0,
// 					value:100
// 				}
// 			})